import json
import os
import urllib.parse
import urllib.request
import mock
import time as t


#fp = open("E:/BeneVision.txt")  # 读取接收到的txt文档，路径可更改
work_dir = os.getcwd()
fp = open(work_dir + os.sep + "BeneVision.txt") #兼容Unix / Windows 系统目录
list = []
line = fp.readline()
list.append(line)
while line:
    # print (line)
    line = fp.readline()
    list.append(line)  # 提取txt文档内容，逐行提取并存入列表
fp.close()
list.append(' ')

list1 = []
list2 = []


# 定义查找函数
def str_find(str1, str2):
    a = 0
    b = 0
    if str1.find(str2) > 0:
        a = str1.find(str2)
        while str1[a] != '|':
            a += 1
        a += 1
        b = a
        while str1[a] != '|':
            a += 1
        a += 1
        b = a
        while str1[a] != '|':
            a += 1
        # print(str2, ' ', str1[b:a])
        list1.append(str2)
        list2.append(str1[b:a])
    return 0


def str_find1(str1, str2):
    a = 0
    if str1.find(str2) > 0:
        a = str1.find(str2)
        while str1[a] != '|':
            a += 1
        a += 1
        while str1[a] != '|':
            a += 1
        a += 1
        # print(str2, ' ', str1[a:])
        list1.append(str2)
        list2.append(str1[a:])
    return 0


x = 0
y = 0
n = 0

if list[0].find('MINDRAY_N-SERIES') > 0:
    x = list[0].find('MINDRAY_N-SERIES')
    while list[0][x] != '^':
        x += 1
    x += 1
    y = x
    while list[0][x] != '^':
        x += 1
if list[0].find('||||') > 0:
    pass
# 对每行内容进行循环查找，并将名称与数据内容，对应地存入两个列表
while len(list[n]) > 1:
    if list[n].find('||||') > 0:
        list1.append('Date')
        list2.append(list[n][list[n].find('||||') + 4:list[n].find('||||') + 18])
        # print('DATE', list[0][list[0].find('||||') + 4:list[0].find('||||') + 18])
    # if list[n].find('PULS_OXIM_SAT_O2'):
    str_find(list[n], 'PULS_OXIM_SAT_O2')
    # if list[n].find('ECG_ELEC_POTL_II'):
    str_find(list[n], 'ECG_ELEC_POTL_II')
    # if list[n].find('PULS_OXIM_PLETH'):
    str_find(list[n], 'PULS_OXIM_PLETH')
    # if list[n].find('PULS_OXIM_PULS_RATE'):
    str_find(list[n], 'PULS_OXIM_PULS_RATE')
    # if list[n].find('ATTR_SAMP_RATE'):
    str_find(list[n], 'ATTR_SAMP_RATE')
    # if list[n].find('BLD_PERF_INDEX'):
    str_find(list[n], 'BLD_PERF_INDEX')
    # if list[n].find('ATTR_NU_MSMT_RES'):
    str_find(list[n], 'ATTR_NU_MSMT_RES')
    # if list[n].find('EVT_INOP'):
    str_find1(list[n], 'EVT_INOP')
    # if list[n].find('IMPED_TTHOR'):
    str_find(list[n], 'IMPED_TTHOR')
    n = n + 1

result_list1 = []
result_list2 = []

count = -1
for y in range(0, len(list1)):
    if y < len(list1) - 1 and list1[y] == "Date" and list1[y + 1] == "Date":
        result_list1.append([])
        result_list2.append([])
        count = count + 1
    result_list1[count].append(list1[y])
    result_list2[count].append(list2[y])


def find_time(i, j):
    temp = j
    while i > 0:
        if result_list1[i][temp] == "Date":
            return result_list2[i][temp]
        else:
            temp = temp - 1


no_wave_data = ["PULS_OXIM_SAT_O2", "PULS_OXIM_PULS_RATE", "BLD_PERF_INDEX"]
wave_data = ["ECG_ELEC_POTL_II", "PULS_OXIM_PLETH", "IMPED_TTHOR"]

result_list = []
# 对二维数组创建字典
for i in range(0, len(result_list1)):
    data = []
    date = {}
    for j in range(1, len(result_list1[i])):
        if result_list1[i][j] in no_wave_data:
            data.append({result_list1[i][j - 1]: result_list2[i][j - 1], result_list1[i][j]: result_list2[i][j]})
        if result_list1[i][j] in wave_data and j + 3 < len(result_list1[i]):
            time = find_time(i, j)
            if not (time in date.keys()):
                date[time] = []
            date[time].append({result_list1[i][j]: result_list2[i][j], result_list1[i][j + 1]: result_list2[i][j + 1],
                               result_list1[i][j + 2]: result_list2[i][j + 2],
                               result_list1[i][j + 3]: result_list2[i][j + 3]})
    if len(date) != 0:
        for k in date.keys():
            data.append({"Date":k,"waveData":date[k]})
    root = {result_list1[i][0]: result_list2[i][0], "data": data}
    result_list.append(root)


# 转换为json的格式化输出
data2 = json.dumps(result_list[-1], sort_keys=True, indent=4, separators=(',', ': '))
print(result_list[-1])
out_file_name = "test.json"
fo = open(work_dir + os.sep + out_file_name, "w")
fo.write(data2)
fo.close()
print('[dataselect.py] 生成文件成功, file：' + out_file_name)

data2 = json.loads(data2)


req_url = "http://42.193.110.73/v1/recv"

# mock 10次数据发送
for i in range(10):
    data_mock = bytes(mock.get_mock_data(), 'utf8')
    resp = urllib.request.urlopen(url = req_url, data = data_mock).read()
    print('[dataselect.py] 发送第' + str(i) + '次Mock数据成功')
    t.sleep(1)

